/********************************************************************************
 * Copyright(c) 2020-2025 BST All rights reserved.
 * - Filename
 * - Author
 * - Version V1.0.0
 * - Date    2023/07/04
 * - Brief
 * - FunctionList:
 ******************************************************************************
 * History:
 *
 *
 *
 ******************************************************************************
 */

#include "Replayer.hpp"
#include "TimeUtil.h"
#include <condition_variable>
#include <csignal>
#include <fstream>
#include <iostream>
#include <mutex>
#include "log.h"

const static char *RETAIN(TAG){"Replay-Main"};

using namespace std;

static mutex mExitMutex;
static condition_variable mExitCond;
static bool mExit = false;
TimeUtil::FpsCalc _fps{};

static void sigtermHandler(int sig)
{
    LOG_I(TAG, "Get signal {}", strsignal(sig));
    {
        lock_guard<mutex> lock(mExitMutex);
        mExit = true;
    }
    mExitCond.notify_one();
}

static void waitForExit()
{

    mExit = false;
    signal(SIGHUP, SIG_IGN);         // 连接挂断
    signal(SIGQUIT, SIG_IGN);        // 终端退出
    signal(SIGPIPE, SIG_IGN);        // 向无读进程的管道写数据
    signal(SIGTTOU, SIG_IGN);        // 后台程序尝试写操作
    signal(SIGTTIN, SIG_IGN);        // 后台程序尝试读操作
    signal(SIGTERM, sigtermHandler); // 终止
    signal(SIGINT, sigtermHandler);  // 终端中
    unique_lock<mutex> lock(mExitMutex);
    mExitCond.wait(lock, [&]
                   { return mExit; });
}

int main(int argc, const char *argv[])
{
    LOGI(TAG, ":::");
    if (argc != 2)
    {
        LOGE(TAG, "Please input config json file ...!");
    }

    std::string cfgFile = argv[1];
    auto player = std::make_shared<Replayer>(cfgFile);
    player->start();
    waitForExit();
    player->stop();
    LOGI(TAG, "~~~");
}
